package redbencity.com.richtext.richeditor;

import android.graphics.Typeface;
import android.text.Spanned;
import android.text.style.StyleSpan;
import android.util.Log;
import android.widget.EditText;


public class ItalicStyle<T extends StyleSpan> extends AbstractTextStyle<T> {
    private String TAG = "ItalicStyle";


    ItalicStyle(Class<T> spanType, int type) {
        super(spanType, type);
        if (type != TextStyleFactory.ITALIC_SPAN) {
            throw new IllegalArgumentException("must italic span");
        }
    }


    @Override
    void cursorPositionChanged(EditText currentEditText, int start, int digits) {
        T[] typeSpans = currentEditText.getEditableText()
                .getSpans(start + digits - 1, start + digits, this.spanType);
        for (T typeSpan : typeSpans) {
            if (typeSpan.getStyle() == Typeface.ITALIC) {
                cursorPositionChangeListener.setCursorPositionChangeListener(this.type);
                isSelect = true;
            }
        }
    }

    @Override
    void inputTextChanged(EditText currentEditText, int start, int count) {
        T[] typeSpans = currentEditText.getEditableText().getSpans(start - 1, start, this.spanType);
        boolean isExist = false;
        for (T typeSpan : typeSpans) {
            if (typeSpan.getStyle() == Typeface.ITALIC) {
                isExist = true;
                if (!isSelect) {
                    int spanStart = currentEditText.getEditableText().getSpanStart(typeSpan);
                    int spanEnd = currentEditText.getEditableText().getSpanEnd(typeSpan);
                    Log.d(TAG, "  currentEditText.getSelectionStart() " + currentEditText.getSelectionStart()
                            + " spanStart " + spanStart + " spanEnd " + spanEnd + " start " + start + " count " + count);
                    currentEditText.getEditableText().removeSpan(typeSpan);
                    currentEditText.getEditableText().setSpan(TextStyleFactory.createCharacter(this.type), spanStart, start, Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
                    if (spanEnd - start - count > 0) {
                        currentEditText.getEditableText().setSpan(TextStyleFactory.createCharacter(this.type), start + count, spanEnd, Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
                    }
                }
            }
        }
        if (!isExist && isSelect) {
            currentEditText.getEditableText().setSpan(TextStyleFactory.createCharacter(this.type), start, start + count, Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
        }
    }

}


